const { checkinApi } = require('../../../../utils/api');
const auth = require('../../../../utils/auth');

Page({
  data: {
    // 筛选条件
    filters: {
      status: 'all', // all, active, completed, upcoming
      classId: '',
      keyword: ''
    },
    // 筛选选项
    statusOptions: [
      { value: 'all', label: '全部' },
      { value: 'active', label: '进行中' },
      { value: 'completed', label: '已完成' },
      { value: 'upcoming', label: '即将开始' }
    ],
    // 打卡活动列表
    checkinList: [],
    // 页面状态
    loading: false,
    refresherTriggered: false,
    noMore: false,
    currentPage: 1,
    pageSize: 10,
    // 搜索相关
    searchVisible: false,
    searchKeyword: ''
  },

  onLoad(options) {
    console.log('全部打卡页面加载');
    this.loadCheckinList();
  },

  onShow() {
    this.loadCheckinList();
  },

  // 加载打卡活动列表
  async loadCheckinList(refresh = false) {
    try {
      if (refresh) {
        this.setData({
          currentPage: 1,
          noMore: false
        });
      }

      this.setData({ loading: true });

      // 模拟API调用
      const mockData = this.generateMockData();
      
      if (refresh) {
        this.setData({
          checkinList: mockData
        });
      } else {
        this.setData({
          checkinList: [...this.data.checkinList, ...mockData]
        });
      }

      // 模拟分页结束
      if (this.data.currentPage >= 3) {
        this.setData({ noMore: true });
      }

    } catch (error) {
      console.error('加载打卡活动失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refresherTriggered: false
      });
    }
  },

  // 生成模拟数据
  generateMockData() {
    const statuses = ['active', 'completed', 'upcoming'];
    const titles = [
      '每日阅读打卡',
      '数学练习打卡', 
      '英语单词背诵',
      '体育锻炼打卡',
      '科学实验打卡',
      '艺术创作打卡',
      '社会实践打卡',
      '劳动技能打卡'
    ];
    
    const data = [];
    for (let i = 0; i < this.data.pageSize; i++) {
      const status = statuses[Math.floor(Math.random() * statuses.length)];
      const title = titles[Math.floor(Math.random() * titles.length)];
      
      data.push({
        id: this.data.currentPage * this.data.pageSize + i + 1,
        title: title,
        status: status,
        classId: 2504 + Math.floor(Math.random() * 3),
        className: `六年级${Math.floor(Math.random() * 3) + 1}班`,
        participants: Math.floor(Math.random() * 30) + 10,
        totalDays: Math.floor(Math.random() * 20) + 5,
        completedDays: Math.floor(Math.random() * 15) + 1,
        startDate: '2024-01-15',
        endDate: '2024-01-30',
        creator: '张老师',
        rewardPoints: Math.floor(Math.random() * 50) + 10,
        description: '这是一个有趣的打卡活动，旨在培养学生的良好习惯。'
      });
    }
    
    return data;
  },

  // 下拉刷新
  async onRefresh() {
    console.log('下拉刷新');
    this.setData({
      refresherTriggered: true
    });
    
    await this.loadCheckinList(true);
    
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000
    });
  },

  // 上拉加载更多
  async onLoadMore() {
    if (this.data.loading || this.data.noMore) {
      return;
    }

    console.log('上拉加载更多');
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    
    await this.loadCheckinList();
  },

  // 状态筛选
  onStatusFilter(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      'filters.status': status
    });
    
    this.loadCheckinList(true);
  },

  // 搜索
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 执行搜索
  onSearch() {
    this.setData({
      'filters.keyword': this.data.searchKeyword,
      searchVisible: false
    });
    
    this.loadCheckinList(true);
  },

  // 显示搜索框
  onShowSearch() {
    this.setData({
      searchVisible: true
    });
  },

  // 隐藏搜索框
  onHideSearch() {
    this.setData({
      searchVisible: false,
      searchKeyword: '',
      'filters.keyword': ''
    });
    
    this.loadCheckinList(true);
  },

  // 查看活动详情
  onCheckinDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/class/checkin/detail/index?id=${id}`
    });
  },

  // 编辑活动
  onEditCheckin(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/class/checkin/edit/index?id=${id}`
    });
  },

  // 删除活动
  onDeleteCheckin(e) {
    const id = e.currentTarget.dataset.id;
    const title = e.currentTarget.dataset.title;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${title}"吗？删除后无法恢复。`,
      success: (res) => {
        if (res.confirm) {
          this.deleteCheckin(id);
        }
      }
    });
  },

  // 删除打卡活动
  async deleteCheckin(id) {
    try {
      wx.showLoading({ title: '删除中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 从列表中移除
      const checkinList = this.data.checkinList.filter(item => item.id !== id);
      this.setData({ checkinList });
      
      wx.hideLoading();
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 创建新活动
  onCreateCheckin() {
    wx.navigateTo({
      url: '/pages/class/checkin/create-checkin/index'
    });
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'active': '进行中',
      'completed': '已完成', 
      'upcoming': '即将开始'
    };
    return statusMap[status] || '未知';
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'active': '#43e97b',
      'completed': '#667eea',
      'upcoming': '#ff9a9e'
    };
    return colorMap[status] || '#999';
  }
});